import os
import zipfile
import yaml
import shutil
import paramiko
import getpass

repoHost="vsys01775"
repoUser="blokhin_sn"
repoPath="/home/blokhin_sn/repo/"
metafile="metadata.yml"

if __name__=="__main__":
    try:
        print("make distributive archive")
        dist_path = os.path.dirname(os.path.realpath(__file__))+"\\dist"
        with open(metafile,mode="r",encoding="UTF-8") as f:
            metadata = yaml.load(f, Loader=yaml.FullLoader)
            version = metadata["Version"]
            productName = metadata["ProductName"]
            zipName = f"{dist_path}\\{productName}-v.{version}.zip"
            print(f"zip name: {zipName}")
            zf = zipfile.ZipFile(zipName, "w",zipfile.ZIP_DEFLATED)
            for dirname, subdirs, files in os.walk(f"{dist_path}\\{productName}"):
                zf.write(dirname,dirname.replace(f"{dist_path}\\",""))
                for filename in files:
                    itemName=os.path.join(dirname, filename)
                    arcName = itemName.replace(f"{dist_path}\\","")
                    zf.write(itemName,arcName)
                    print(arcName)
            zf.close()
        shutil.copyfile(metafile,f"{dist_path}\\{metafile}")
        print("local copy done")
        print("copy distributive to repo")
        ssh = paramiko.SSHClient()
        ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
        passw = getpass.getpass(f"Пароль {repoUser}@{repoHost}:")
        ssh.connect(repoHost,username=repoUser,password=passw)
        print(f"{repoHost} connected")
        sftp = ssh.open_sftp()
        remotepath=f"{repoPath}{productName}-v.{version}.zip"
        print("sftp opened")
        sftp.put(zipName,remotepath)
        sftp.put(metafile,f"{repoPath}{metafile}")
        print("files puted")
        sftp.close()
        ssh.close()
        print("connection closed")
    except Exception as exp:
        print(f"archive error: {exp}")